package com.example.im.ui.abstracts

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
//import butterknife.ButterKnife
//import butterknife.Unbinder
import com.trello.rxlifecycle2.LifecycleTransformer
import com.trello.rxlifecycle2.android.FragmentEvent
import com.trello.rxlifecycle2.components.support.RxFragment
import com.example.im.mvp.base.BasePresenter
import com.example.im.mvp.base.BaseView

abstract class AbstractBaseFragment<P : BasePresenter<*>> : RxFragment(), BaseView {

    var mPresenter: P? = null

    private var mView: View? = null
    private var isLazyLoad: Boolean = false
    private var isCreateView: Boolean = false
    private var isVisible: Boolean? = false

    abstract val layoutId: Int

    abstract fun initView()

    abstract fun initPresenter()

    abstract fun initLazyLoad()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (mView == null) {
            mView = inflater.inflate(layoutId, container, false)
            isCreateView = true
        }
        return mView
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initView()
        initPresenter()
        onVisible()
    }


    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (userVisibleHint) onVisible() else onInvisible()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (mPresenter != null) mPresenter!!.detachView()
    }


    override fun onSuccess() {

    }

    override fun onHint(hint: String) {
        Toast.makeText(activity, hint, Toast.LENGTH_SHORT).show()
    }

    override fun <T> bindToLife(): LifecycleTransformer<T> {
        return bindUntilEvent(FragmentEvent.STOP)
    }

    private fun onVisible() {

        isVisible = true

        if (isLazyLoad) {
            onRefreshLoad()
        }
        if (!isLazyLoad && isCreateView && userVisibleHint) {
            isLazyLoad = true
            initLazyLoad()
        }
    }

    private fun onInvisible() {
        isVisible = false
    }

    open fun onRefreshLoad() {}

}